# coding: utf-8
class DocController < ApplicationController

  include ApplicationHelper

  # GET: 列表页
  def index

    return unless unlogin

    # 当前类别
    cateid = params[:cateid]
  	@user = session[:user]
    if(cateid == nil)
      @doclist = @user.docmains.select('id, userid, cateid, title, wordcount, shareid, updated_at').includes(:cates).paginate(:page => params[:page], :per_page => 20).order("updated_at desc")
    else
      @doclist = @user.docmains.select('id, userid, cateid, title, wordcount, shareid, updated_at').includes(:cates).where(:cateid => cateid).paginate(:page => params[:page], :per_page => 20).order("updated_at desc")
    end

  end

  # 详情页
  def show
    return unless unlogin
    @user = session[:user]
    @doc = DocMain.find(params[:docid])
    @page_title = "#{@doc.title} - 天天笔记"

    # 最近文档
    if(cookies[:last_docids] != nil)
      ids = cookies[:last_docids]
      ids = ids.gsub('|', ',')
      @lastdocs = DocMain.select('id, title').where("userid=#{@user.id} and id in(#{ids}) and id != #{@doc.id}").limit(5);
    end

    render :text => '非法访问' if(@doc.userid != @user.id)
  end

  # A类型最终页
  def showa
    @selfuser = false
    viewAuth = false # 没有显示权限
    docid = DocBll.decode(params[:docid])
    @user = session[:user]
    @doc = DocMain.find(docid)
    if(@doc != nil)
      unless(viewAuth)
        if(@user != nil && @user[:id] == @doc[:userid])
          viewAuth = true
          @selfuser = true # 用户本人查看
        end
      end

      viewAuth = @doc[:shareid] == 1 unless(viewAuth)
    end

    if(viewAuth)
      if(@doc != nil)
        @page_title = "#{@doc.title} - 天天笔记"

        # 最近文档
        if(cookies[:last_docids] != nil && @user != nil)
          ids = cookies[:last_docids]
          ids = ids.gsub('|', ',')
          @lastdocs = DocMain.select('id, title').where("userid=#{@user.id} and id in(#{ids}) and id != #{@doc.id}").limit(5);
        end

      end

      render :template => 'doc/show.html.erb'
    else
      render :status => 404, :text => '您没有权限查看该文档' unless(viewAuth)
    end

  end

  # GET: 分享页
  def share
    @doc = DocMain.find(params[:docid])
    if(@doc.shareid != 1)
      render :text => '该文档没有设置为分享状态，或者已取消分享。'
    else
      redirect_to ("/doc/show/%sa.html" % DocBll.encode(@doc[:id])), :status => 301
    end
  end

  # GET：分享页面第二版
  def share2
    @doc = DocMain.find(params[:docid])
    if(@doc.shareid != 1)
      render :text => '该文档没有设置为分享状态，或者已取消分享。' 
    else
      redirect_to ("/doc/show/%sa.html" % DocBll.encode(@doc[:id])), :status => 301
    end
  end

  # 删除单条文档
  def delete

    return unless unlogin
    return if request.get? # 不支持 get 请求

    # 删除
    delete_ok = 0
    @doc = DocMain.find(params[:docid])
    if(@doc != nil && @doc.userid == session[:user].id)
      @doc.destroy
      delete_ok = 1
    end

    render :text => delete_ok.to_s
  end

  # GET: 新建/修改
  def new
    return unless unlogin
    @user = session[:user]
    if(params[:docid] == nil)
      @isAdd = true
      @doc = DocMain.new
    else
      @isAdd = false
      @doc = DocMain.find(params[:docid]) # 修改文档
      @page_title = "∷ #{@doc.title} - 修改文档 - 天天笔记"
      @detail_url = getDetailUrl(@doc)

      # 最近文档
      if(cookies[:last_edit_docids] != nil)
        ids = cookies[:last_edit_docids]
        ids = ids.gsub('|', ',')
        @lastdocs = DocMain.select('id, title').where("userid=#{@user.id} and id in(#{ids}) and id != #{@doc.id}").limit(5);
      end

      render :text => '非法访问' if(@doc.userid != @user.id)
    end
  end

  # GET: 通过docid来获取最终页的url链接
  def detailUrl
    url = ''
    begin
      if(session[:user] != nil)
        doc = DocMain.find(params[:docid])
        if(doc != nil)
          p '开始： '
          url = getDetailUrl(doc)
          p 'url: ' << url
        end
      end      
    rescue Exception => e
      puts e
    end
    render :text => "{ \"url\":\"#{url}\" }"
  end

  # POST: ajax方法保存文档
  def saveDoc
    return unless unlogin
    return if request.get? # 不支持 get 请求

    begin
      @user = session[:user]
      code = 0 # 失败(0), 成功(1)
      docID = 0
      docID = params[:id].to_i if(params[:id] != nil)
      if(docID > 0)
        docs = DocMain.where({:id => docID, :userid => @user.id})
        doc = docs[0] if(docs.length > 0)
      else
        doc = DocMain.new
      end
      if(doc != nil)
        doc[:userid] = @user.id
        doc[:title] = params[:title]
        doc[:cateid] = params[:cateid]
        doc[:content] = params[:content]
        doc[:wordcount] = params[:wordcount]
        doc[:shareid] = params[:shareid]
        code = doc.id if(doc.save)
      end
    rescue Exception => e
      puts e
    end
    render :text => code
  end

  def create
    return unless unlogin
  	@doc = DocMain.new(params[:doc_main])
  	@doc.userid = session[:user].id

  	respond_to do |format|
  	  if @doc.save
  	    format.html { redirect_to action: "index", notice: 'save_successfully' }
  	    format.json { render json: @doc, status: :created, location: @doc }
  	  else
  	    format.html { render action: "new" }
  	    format.json { render json: @doc.errors, status: :unprocessable_entity }
  	  end
  	end
  end

  # PUT: 修改动作
  def update
    
    return unless unlogin
    @doc = DocMain.find(params[:docid])
    #render :text => "Hello : " << @doc.shareid << ' - ' << @doc.title;  return;
    respond_to do |format|
      @doc.stateid = 0 # 修改文档后将推荐标记移除
      if @doc.update_attributes(params[:doc_main])
        format.html { redirect_to action: "index", notice: 'save_successfully' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @doc.errors, status: :unprocessable_entity }
      end
    end
  end

  #—————————————————————————————————— 类别配置管理 ————————————————————————# 

  # GET: 类别配置
  def cate_conf
    @user = session[:user]
    @catelist = @user.doccategorys.find(:all, :order=>'sortid asc')
    render :template => 'doc/cate.html.erb'
  end

  # POST: 类别删除
  def cate_delete
    code = 0 # 失败(0), 成功(1), 类别中含有文档(-1)
    begin
      user = session[:user]
      cateid = params[:id]
      if(cateid != nil)
        docCate = DocCategory.find_by_id_and_userid(cateid.to_i, user.id)
        if(docCate != nil)
          # 如果该用户的类别个数大于1个则允许删除
          if(user.doccategorys.count > 1)
            count = DocMain.where(:cateid=>cateid.to_i, :userid=>user.id).count # 查询该类别中的文档个数
            if(count == 0)
              docCate.destroy
              code = 1 # 删除成功
            else
              code = -1 # 类别中含有文档
            end            
          end
        end
      end
    rescue Exception => e
      puts e
    end    
    render :text => code
  end

  # POST: 类别保存
  def cate_save
    code = 0
    begin
      cateid = params[:id]
      name = inputString(params[:name], 8) || '未命名类别'
      name = '未命名类别' if(name == '')
      sortid = params[:sortid].to_i

      # 检查该用户是否有类别权限
      docCate = DocCategory.find_by_id_and_userid(cateid.to_i, session[:user].id)
      if(docCate != nil)
        docCate[:name] = name
        docCate[:sortid] = sortid
        docCate.save
        code = 1 # 修改成功
      end
    rescue Exception => e
      puts e
    end
    render :text => code
  end

  # POST: 类别新增
  def cate_new
    code = 0 # 失败(0), 成功(1), 已达到最大配置数(-1)
    begin
      name = inputString(params[:name], 8) || '未命名类别'
      name = '未命名类别' if(name == '')
      sortid = params[:sortid].to_i

      # 检查该用户是否超过类别配置的最大限制数
      count = session[:user].doccategorys.count
      if(count >= 6)
        code = -1 # 已达到最大配置数
      else
        cate = DocCategory.new
        cate[:userid] = session[:user].id
        cate[:name] = name
        cate[:sortid] = sortid
        cate.save
        code = 1 # 保存成功
      end
    rescue Exception => e
      puts e
    end
    render :text => code
  end

  #—————————————————————————————————— 后台管理 ————————————————————————# 

  # GET: 后台文档审核
  def check
    return unless checkAdmin
    @doclist = DocMain.select('id, userid, title, shareid, stateid, updated_at').includes(:user).where(:shareid => 1).paginate(:page => params[:page], :per_page => 10).order("updated_at desc")
    render :template => 'admin/doc.html.erb'
  end

  # POST: 首页推荐
  def check_passindex
    return unless checkAdmin
    count = 0
    doclist = DocMain.find(params[:ids].split(','))
    doclist.each do|doc|
      if(doc.stateid == 1)
        doc.stateid = 0
      else  
        doc.stateid = 1
      end
      doc.update_column('stateid', doc.stateid)
      # doc.record_timestamps = false
      # doc.save
      count = count.next
    end
    render :text => count
  end

  # GET: 后台-文档列表
  def admin_doclist
    return unless checkAdmin
    @doclist = DocMain.select('id, userid, title, shareid, wordcount, stateid, created_at, updated_at').paginate(:page => params[:page], :per_page => 10).order("updated_at desc")
    render :template => 'admin/doclist.html.erb'
  end

private

  def unlogin
    # 未登录状态
    if(session[:user] == nil)
      redirect_to :action => 'login', :controller =>'user'
      return false
    end
    true
  end

end
